<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="auto"
    >
      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入课程名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程组名称" prop="groupId">
        <el-select
          v-model="queryParams.groupId"
          placeholder="请选择会员等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon class="mr-5px" icon="ep:search" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon class="mr-5px" icon="ep:refresh" /> 重置</el-button>
        <el-button
          v-hasPermi="['train:course:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" /> 新增
        </el-button>
        <el-button
          v-hasPermi="['train:course:export']"
          :loading="exportLoading"
          plain
          type="success"
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" /> 导出
        </el-button>
        <el-button
          v-hasPermi="['train:course:delete']"
          :disabled="isEmpty(checkedIds)"
          plain
          type="danger"
          @click="handleDeleteBatch"
        >
          <Icon class="mr-5px" icon="ep:delete" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      row-key="id"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="序号" width="60">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="课程名称" prop="name" />
      <el-table-column align="center" label="课程组" prop="groupId">
        <template #default="scope">
          {{ groupList.find((item) => item.id === scope.row.groupId)?.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="课程排序" prop="courseSort" >
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.courseSort }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180px"
      />
      <el-table-column align="center" label="操作" min-width="120px">
        <template #default="scope">
          <el-button
            v-hasPermi="['train:course:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['train:course:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CourseForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { Course, CourseApi } from '@/api/train/course'
import CourseForm from './CourseForm.vue'
import { CourseGroupApi } from '@/api/train/coursegroup'

/** 课程 列表 */
defineOptions({ name: 'Course' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Course[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const groupList = ref([]) // 课程组列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  groupId: undefined,
  price: undefined,
  intro: undefined,
  duration: undefined,
  singleLessonDuration: undefined,
  courseCover: undefined,
  courseSort: undefined,
  beginDate: [],
  endDate: [],
  vipRequired: undefined,
  status: undefined,
  createTime: [],
  enrollments: undefined,
  courseMark: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CourseApi.getCoursePage(queryParams)
    const pageParams = reactive({
      pageSize: 100
    })
    const group = await CourseGroupApi.getCourseGroupPage(pageParams)
    groupList.value = group.list
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CourseApi.deleteCourse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除课程 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await CourseApi.deleteCourseList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Course[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CourseApi.exportCourse(queryParams)
    download.excel(data, '课程.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 上架状态修改  */
function handleStatusChange(row) {
  let text = row.status === 0 ? '上架' : '下架'
  message
    .confirm('确认要' + text + '吗?')
    .then(function () {
      return CourseApi.changeStatus(row)
    })
    .then(() => {
      message.success(text + '成功')
    })
    .catch(function () {
      row.status = row.status === 0 ? 1 : 0
    })
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
